#!/public/home/jwli/workSpace/yongkang/.nvm/versions/node/v16.20.2/bin/node
const path = require("path");
const fs = require("fs");
const { get_res, proces_funcs } = require("./utils/get_res");
const { ls } = require("./utils/ls");
const { write2output } = require("./utils/stream");

const argv = require("minimist")(process.argv.slice(2));

const workDir = argv.dir;
if (!argv.output) {
  argv.output = path.resolve(
    workDir,
    `output_${argv.benchmark}_${argv.type}.csv`
  );
}
console.log(argv);

const removeFileSuffix = (filePath, newSuffix) =>
  filePath.replace(/\.[^.]+$/, "");
const replaceFileSuffix = (filePath, newSuffix) =>
  filePath.replace(/\.[^.]+$/, `.${newSuffix}`);

// "/Users/lic/bench_res-new-21FP-js/23.1216/bench_VMCAI-ltlfsyn_SATtrace";
const { names, folderList } = require("./utils/benchmark")[argv.benchmark];

async function main(outputFilePath) {
  const titleLine = "Folder, Filename, Result\n";
  fs.truncate(outputFilePath, 0, (err) => {});
  fs.appendFile(outputFilePath, titleLine, (err) => {});

  const pattern = "*.ltlf"; // Replace with the wildcard pattern you want to match

  // p-task-sequences
  let p = Promise.resolve();

  for (let index = 0; index < folderList.length; index++) {
    const folder = folderList[index];
    const folderId = names[index];
    const directoryPath = path.resolve(workDir, folder); // Replace with the actual directory path
    const { fileList } = await ls(directoryPath, pattern);
    if (!fileList) {
      console.error(`Error: folder ${folder} is not exist!`);
      continue;
    }
    // console.log(fileList);
    // const fileSet = new Set(fileList);
    const mappedPromiseArray = fileList.map(async (filename) => {
      // console.log(filename);
      // if (filename!="f57.ltlf")
      //   return {folderId, filename: removeFileSuffix(filename), result: "skip"};
      const { result } = await get_res(
        path.resolve(directoryPath, replaceFileSuffix(filename, "res")),
        proces_funcs[argv.type].just_res
      );
      // fileSet.delete(filename);
      // if (fileSet.size < 10)
      // {
      //   console.log(fileSet);
      // }
      // console.log(result, folderId, filename);
      return {
        folderId,
        filename: removeFileSuffix(filename),
        result,
      };
    });
    const all_finished = Promise.all(mappedPromiseArray);
    // add current output task into p-task-sequences
    p = p.then(async () => {
      const results = await all_finished;
      return write2output(results, outputFilePath);
    });
  }
}

main(argv.output);
